package org.raymond.iworks.study.basic.thread.readwritelock;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
public class Demo1 {
    static int count = 0;

    public static void main(String[] args) {
        ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
        Lock readLock = readWriteLock.readLock();
        Lock writeLock = readWriteLock.writeLock();
        ThreadPoolExecutor poolTaskExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

        Runnable rr = ()->{
            readLock.lock();
            try {
                Thread.sleep(1000);
                System.out.println("count:"+count);
            } catch (InterruptedException e) {
            } finally {
                readLock.unlock();
            }
        };

        Runnable wr = ()->{
            writeLock.lock();
            try {
                count++;
            } finally {
                writeLock.unlock();
            }
        };
        poolTaskExecutor.execute(rr);
        poolTaskExecutor.execute(wr);
        poolTaskExecutor.execute(rr);

        poolTaskExecutor.shutdown();
    }
}
